from threading import Thread, Lock
import time


class MyThread(Thread):
    """继承Thread类创建线程
    """
    def run(self):
        global num
        time.sleep(1)

        # 上锁，并指定超时时间
        if mutex.acquire(1):
            num = num+1
            msg = self.name+' set num to '+str(num)
            print(msg)
            # 释放锁
            mutex.release()


num = 0
mutex = Lock()

def main():
    for i in range(5):
        t = MyThread()
        t.start()


if __name__ == '__main__':
    main()
    